<template>
    <div class="getAll">
        <a-form
        layout="inline"
        style="margin-bottom:15px"
        autocomplete="off"
        >
            <a-form-item>
                <a-input placeholder="主目录" v-model:value="homeDirectory">
                </a-input>
            </a-form-item>
            <a-form-item>
                <a-button
                type="primary"
                html-type="submit"
                @click="addHomeDirectory(homeDirectory)"
                :disabled="homeDirectory===''"
                >
                添加
                </a-button>
            </a-form-item>


            <a-form-item>
                <a-input placeholder="搜索" v-model:value="search">
                </a-input>
            </a-form-item>
            <a-form-item>
                <a-button
                shape="circle"
                type="primary"
                html-type="submit"
                @click="searchCategory(search)"
                :disabled="search===''"
                >
                <template #icon><SearchOutlined /></template>
                </a-button>
            </a-form-item>
        </a-form>

        
        <a-table :columns="columns" :data-source="bookmarkClassList" rowKey='cid'>
            <template #bodyCell="{ column,record }" >
                <template v-if="['title'].includes(column.dataIndex)">
                    <div>
                    <a-input
                        v-if="editableData[record.cid]"
                        v-model:value="editableData[record.cid]['title']"
                        style="width:60%"
                    />

                    <a-tree
                        :tree-data="cloneData[record.cid]"
                        v-if="editableData[record.cid]"
                        v-model:selectedKeys="selectedKeys"
                        :fieldNames="{children:'children', title:'title', key:'cid' }"
                    >
                        <!-- <span>{{ record.title }}</span> -->
                        <template>{{ record.title }}</template>
                    </a-tree>
                    <template v-else>
                        {{ record.title }}
                    </template>
                    </div>
                </template>

                <template v-if="column.dataIndex === 'action'">
                    <a-popconfirm      
                    v-if="bookmarkClassList.length" 
                    title="你确定要删除吗?"
                    okText="确定"
                    cancelText="取消"
                    @confirm="deleteCategory(record)"
                    >
                        <a-button type="primary" danger>删除</a-button>
                    </a-popconfirm>


                    <span v-if="editableData[record.cid]">
                        <a-popconfirm 
                        @confirm="save(editableData[record.cid])" 
                        title="你确定要保存吗?"
                        okText="确定"
                        cancelText="取消">
                            <a-button type="dashed">保存</a-button>
                        </a-popconfirm>
                        <a-button @click="cancel(record.cid)" type="dashed">取消</a-button>
                    </span>
                    <span v-else>
                        <a-button type="primary" danger @click="edit(record)">修改</a-button>
                        
                    </span>
                </template>

            </template>
        </a-table>
    </div>
</template>

<script> 
/**
 * 数据来源：@/pages/index/store/bookmarkClass.js
 */
import { defineComponent,computed,ref,reactive,toRaw,watch } from 'vue';
import { cloneDeep } from 'lodash-es';
import { SearchOutlined } from '@ant-design/icons-vue';
import { useStore } from 'vuex';
import { getTreeData } from '@/lib'
export default defineComponent({
    name:'BookmarkClass-getAll',
    components: {
        SearchOutlined,
    },
    setup() {
        const store = useStore();
        let homeDirectory = ref(''); 
        let search = ref(''); 
        let parentId = ref('')
        const newList = [];
        const columns =[{
            title: '分类ID',
            dataIndex: 'cid',
        },{
            title: '分类名称',
            dataIndex: 'title',
        },{
            title: '父级ID',
            dataIndex: 'pid',
        },{
            title: '用户ID',
            dataIndex: 'uid',
        },{
            title: '操作',
            dataIndex: 'action', 
        }];
        let bookmarkClassList = computed(()=>{
            return store.getters.treeData
        })
        
        // let topBookmarkClassList = computed(()=>{
        //     return store.getters.topTreeData
        // })

        // let newBookmarkClassList = computed(()=>{
        //     return cloneDeep(store.state.bookmarkClass.newBookmarkList)
        // })

        const addHomeDirectory = title => {
            store.dispatch('bookmarkClass/asyncAddCategory', {title})
            homeDirectory.value = "";
        }
        const deleteCategory = record => {
            newList.splice(0,newList.length);
            filterData([toRaw(record)])
            newList.reverse().forEach((item,index) => {
                setTimeout(() => {
                    console.log(item);
                    store.dispatch('bookmarkClass/asyncDeleteCategory', {classId:item})
                }, 50*index);
            })
            setTimeout(() => {
                store.dispatch('bookmarkClass/asyncGetBookmarkList')
            }, 50*(newList.length+1));
            // console.log(newList);
        }

        const searchCategory = data => {
            if(+data) store.dispatch('bookmarkClass/asyncGetBookmarkList', {classId:data})
            else store.dispatch('bookmarkClass/asyncGetBookmarkList', {keyword:data})
        }

        // 递归扁平化函数
        function filterData(data) {
            data.forEach(item=>{       
                if(!item.children) {
                    newList.push(item.cid)
                    return false
                } else {
                    newList.push(item.cid)
                    filterData(item.children)
                }
            })
        }

        // let newArr = reactive([]);
        // function dataDelete(data,cid) {
        //     data.forEach(item => {
        //         if(!item.children){
        //             if(item.cid==cid) newArr = data.filter(value => cid != value.cid)
        //             return false
        //         }
        //         else {
        //             if(item.cid==cid) newArr = data.filter(value => cid != value.cid)
        //             dataDelete(item.children,cid)
        //         }
        //     })
        // }
        
        const editableData = reactive({});
        const cloneData = reactive({});

        const edit = record => {
            // console.log([toRaw(record)]);
            // newBookmarkList = dataDelete(record.cid);
            // dataDelete(topBookmarkClassList.value,record.cid);
            // store.commit('bookmarkClass/getNewBookmarkList',newArr)
            // if(localStorage.getItem('cid')){
            //     cancel(localStorage.getItem('cid'))
            // }
            // localStorage.setItem('cid',record.cid);
            newList.splice(0,newList.length);
            filterData([toRaw(record)]);
            let deepClone =  cloneDeep(store.state.bookmarkClass.sourceData.filter(item=>!newList.some(value=>value==item.cid)))
            // store.dispatch('bookmarkClass/asyncGetTreeData', deepClone)
            // console.log(store.state.bookmarkClass.newBookmarkList);
            editableData[record.cid] = cloneDeep(
                store.state.bookmarkClass.sourceData.filter(item => {
                    return record.cid === item.cid
                })[0]
            ); 
            cloneData[record.cid] = cloneDeep([{ title: '顶级分类', pid: '0', cid: '0' },...getTreeData(deepClone)])
            console.log(cloneData[record.cid]);
        };

        const save = value => {
            store.dispatch('bookmarkClass/asyncAmendCategory',{classId:value.cid,title:value.title,pid:toRaw(parentId)[0]})
            delete editableData[value.cid];
        };

        const cancel = cid => {
            delete editableData[cid];
        };

        const selectedKeys = ref([]);

        watch(selectedKeys, () => {
            parentId = selectedKeys.value;
        });

        
        return {
        bookmarkClassList,columns,homeDirectory,search,addHomeDirectory,deleteCategory,searchCategory,editableData,edit,save,cancel,selectedKeys,parentId,cloneData
        }
    },

});
</script>

<style lang="scss">
.ant-btn.ant-btn-primary.ant-btn-dangerous{
    margin-right: 10px;
}
.ant-tree.ant-tree-icon-hide{
    width: 60%;
}
    
</style>